package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.SmsClient;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SpuDescService spuDescService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuAttrValueService skuAttrValueService;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpusByCid(String categoryId, PageParamVo paramVo) {
        LambdaQueryWrapper<SpuEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key = paramVo.getKey();
        if (!StringUtils.equals(categoryId, "0")) {
            queryWrapper.eq(SpuEntity::getCategoryId, categoryId);
        }
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(t -> t.like(SpuEntity::getId, key)
                    .or().like(SpuEntity::getName, key));
        }
        IPage<SpuEntity> page = this.page(paramVo.getPage(), queryWrapper);
        return new PageResultVo(page);
    }

    /*@Override
    public void saveSpuVo(SpuVo spuVo) {
        //1、保存spu的数据
        SpuEntity spuEntity = new SpuEntity();
        BeanUtils.copyProperties(spuVo, spuEntity);
        spuEntity.setCreateTime(new Date());
        spuEntity.setUpdateTime(new Date());
        this.save(spuEntity);
        Long spuId = spuEntity.getId();
        //2、保存spu的商品详情图地址
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        spuDescEntity.setSpuId(spuId);
        spuDescEntity.setDecript(Collections.isEmpty(spuVo.getSpuImages())
                ? null : StringUtils.join(spuVo.getSpuImages(), ","));
        spuDescService.save(spuDescEntity);
        //3、保存spu的基本属性
        List<BaseAttrVo> baseAttrs = spuVo.getBaseAttrs();

        List<SpuAttrValueEntity> spuAttrValueEntities = baseAttrs.stream().map(baseAttrVo -> {
            SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
            BeanUtils.copyProperties(baseAttrVo, spuAttrValueEntity);
            spuAttrValueEntity.setSpuId(spuId);
            spuAttrValueEntity.setSort(0);
            return spuAttrValueEntity;
        }).collect(Collectors.toList());
        spuAttrValueService.saveBatch(spuAttrValueEntities);
        //4、保存sku集合
        List<SkuVo> skus = spuVo.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
            return;
        }
        //4.1 保存sku数据
        for (SkuVo skuVo : skus) {
            SkuEntity skuEntity = new SkuEntity();
            BeanUtils.copyProperties(skuVo, skuEntity);
            skuEntity.setSpuId(spuId);
            skuEntity.setBrandId(spuVo.getBrandId());
            skuEntity.setCategoryId(spuVo.getCategoryId());

            skuEntity.setDefaultImage(CollectionUtils.isEmpty(skuVo.getImages()) ? null :
                    skuVo.getImages().get(0));
            skuService.save(skuEntity);
            Long skuId = skuEntity.getId();
            //4.2 保存sku的图片列表
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty(images)) {

                List<SkuImagesEntity> skuImagesEntities = images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setUrl(image);
                    skuImagesEntity.setSort(0);
                    skuImagesEntity.setDefaultStatus(skuEntity.getDefaultImage()
                            .equals(image) ? 1 : 0);//1默认图  0不是
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

            }
            //4.3 保存sku的销售属性和值
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();

            saleAttrs.forEach(saleAttr -> {
                saleAttr.setSkuId(skuId);
                saleAttr.setSort(0);
            });
            skuAttrValueService.saveBatch(saleAttrs);
            //4.4 保存sku的营销数据：需要远程访问 sms服务
            SkuSalesDto skuSalesDto = new SkuSalesDto();
            BeanUtils.copyProperties(skuVo, skuSalesDto);
            skuSalesDto.setSkuId(skuId);
            smsClient.saveSkuSales(skuSalesDto);
        }
    }*/

    //@GlobalTransactional
    @Transactional
    @Override
    public void saveSpuVo(SpuVo spuVo) {
        //1、保存spu的数据
        Long spuId = saveSpu(spuVo);
        //2、保存spu的商品详情图地址
        spuDescService.saveSpuDesc(spuVo, spuId);

        //3、保存spu的基本属性
        spuAttrValueService.saveSpuBaseAttrs(spuVo, spuId);
        //4、保存sku集合
        skuService.saveSkus(spuVo, spuId);

        try {
            Map<String, String> map = new HashMap<>();
            map.put("spuId", spuId + "");
            map.put("operate", "1");
            rabbitTemplate.convertAndSend("gmall.spu.exchange","goods.save",map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //1、保存spu
    @Transactional
    public Long saveSpu(SpuVo spuVo) {
        SpuEntity spuEntity = new SpuEntity();
        BeanUtils.copyProperties(spuVo, spuEntity);
        spuEntity.setCreateTime(new Date());
        spuEntity.setUpdateTime(new Date());
        this.save(spuEntity);
        return spuEntity.getId();
    }
    //2、保存spudesc

    //3、保存spuattrvalues

    //4、保存sku

}